package img

import (
	"ScreenRead/util/log"
	"bytes"
	"encoding/base64"
	"fmt"
	"image"
	"image/png"
	"net/url"
	"os"
)

// GetFileContentAsBase64 将二进制文件转换为 Base64
func GetFileContentAsBase64(path string) string {
	srcByte, err := os.ReadFile(path)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	return url.QueryEscape(base64.StdEncoding.EncodeToString(srcByte))
}

func ImgToBase64Png(image image.Image) (string, error) {
	var buf bytes.Buffer
	err := png.Encode(&buf, image)
	if err != nil {
		return "", err
	}

	return base64.StdEncoding.EncodeToString(buf.Bytes()), err
}

func Base64PngToImg(base64Png string) (image.Image, error) {
	byts, err := base64.StdEncoding.DecodeString(base64Png)
	if err != nil {
		log.LogObj.Errorln(err)
		return nil, err
	}
	return png.Decode(bytes.NewReader(byts))
}
